var box, tipo_busqueda_actual;
$(function(){
    tipo_busqueda_actual = 'simple';
    updateElements();
    
    $('.sf_admin_actions a').click(function(event) {
        event.preventDefault();
        abrirModal($(this));
        
    });
    
    $('#filter_form_simple').formly();
    $('#filter_form_simple').validationEngine({binded: false});
    
    if (quicksearch != 'false'){
        $('#filters_valor_simple').val(quicksearch);
        tipo_busqueda_actual = 'simple'; 
        buscar(1);
    }
});

function updateElements() {
    //hover states on the static widgets
    $('ul.control li').hover(
        function() {
            $(this).addClass('ui-state-hover');
        }, 
        function() {
            $(this).removeClass('ui-state-hover');
        }
        );
    
    $('#filter_form_simple input, #filter_form_simple select,'+
        '#filter_form_avanzado input, #filter_form_avanzado select').keypress(function(event){
        if ( event.which == 13 ) {
            event.preventDefault();
            buscar(1);
        }
    });
    
    $( "#tabs" ).tabs({
        select: function(event, ui) {
            $('#filter_form_avanzado,#filter_form_simple').validationEngine('hideAll');
        }
    });

    $('#filter_form_avanzado').formly();
    $('#filter_form_avanzado').validationEngine({binded: false});
}

function addCustom(inst){
    var tr = $($(inst).parents('tr')[0]);
    var next = tr.prevAll().length+1;
    var is_the_last = (tr.nextAll().length == 0)  ? 1 : 0;
    var object_new = null;
    $.ajax({
        type: "POST",
        url: url_addCustom,
        data: {
            next : next,
            is_the_last : is_the_last
        },
        success: function(data) {
            tr.after(data);
            object_new = $('.new_custom');
            object_new.removeClass('new_custom');
            object_new.show(700);
            if (is_the_last) {
                tr.find('select[id*=logico]').show(700);
            }
            updateCustomIds();
            
            updateElements();
        }
    });
}

function removeCustom(inst){
    var tr = $($(inst).parents('tr')[0]);

    tr.hide('slow', function() {
        $(this).remove();
        updateCustomIds();
    });

}

function updateCustomIds(){
    var id = "";
    var name ="";
    var tr_index = 0;
    var tr = null;
    $('#filter_custom tr').each(function(index){
        tr_index = index;
        tr = $(this);
        tr.find('select, input').each(function(index){
            id = $(this).attr('id').split('_');
            $(this).attr('id',id[0]+'_'+id[1]+'_'+tr_index+'_'+id[3]);
            name = $(this).attr('name');
            name = name.replace(id[2],tr_index);
            $(this).attr('name',name);
        }); 
    });
    
    if ($('#filter_custom tr').length == 1)
    {
        $($('#filter_custom tr')[0]).find('.remove').hide();
    }else{
        $($('#filter_custom tr')[0]).find('.remove').show();
    }
    
    $($('#filter_custom tr')[$('#filter_custom tr').length-1]).find('select[id*=logico]').hide();
}

function buscar(page){
    var form;
    if (tipo_busqueda_actual == 'simple') {
        form = '#filter_form_simple';
    }else{
        form = '#filter_form_avanzado';
    }
    if ($(form).validationEngine('validate')){
		$.blockUI({
			message: '<img src="/images/ajax-loader_blue.gif" alt="Cargando" title="Cargando"/>',
			css: {
				border: '0px',
				backgroundColor: 'transparent'
			}
		});
		$.ajax({
			type: "POST",
			url: url_buscar,
			data: $(form).serialize()+'&page='+page,
			success: function(data) {
				$('#loader').html(data);
				$('.sf_admin_td_actions a').click(function(event) {
					event.preventDefault();
					abrirModal($(this));
				});
					
				if ($(form).find('#filters_tipo_busqueda').val() == 'simple'){
                                    $('#terminosMasBuscado').hide();
                                    $('#personaQueBuscoEsteTermino').hide();

                                    window.parent.$.ajax({
                                        type: "POST",
                                        url: url_terminos,
                                        data: window.parent.$(form).serialize()+'&page='+page,
                                        success: function(data) {
                                            data = jQuery.parseJSON(data);

                                            $('#terminosMasBuscado div').empty();
                                            jQuery.each(data.terminosMasBuscado, function(index, termino){
                                               $('#terminosMasBuscado div').append('<a href="'+url_index+'?quicksearch='+termino+'">'+termino+'</a><br>');
                                               $('#terminosMasBuscado').show();
                                            });

                                            $('#personaQueBuscoEsteTermino div').empty();
                                            jQuery.each(data.personaQueBuscoEsteTermino, function(index, termino){
                                               $('#personaQueBuscoEsteTermino h4.text').html('Las personas que buscaron "'+$(form).find('#filters_valor_simple').val()+'" tambien buscaron');
                                               $('#personaQueBuscoEsteTermino div').append('<a href="'+url_index+'?quicksearch='+termino+'">'+termino+'</a><br>');
                                               $('#filter_form_simple').parent().removeClass('offset4').addClass('offset2');
                                               $('#personaQueBuscoEsteTermino').show();
                                            });
                                            window.parent.$.unblockUI(); 
                                        }
                                    });
                                }else{
                                    window.parent.$.unblockUI(); 
                                } 
			}
		});
	}
}

function abrirModal(inst){
    var horizontalPadding = 15;
    var verticalPadding = 15;
    $('body').css('overflow','hidden');
    var width = $(window).width();
    var height = $(window).height();
    $('<iframe id="site" src="' + inst.attr('href') + '" />').dialog({
        title: $("#site").contents().find("#sf_admin_container > h1").html(),
        autoOpen: true,
        width: width,
        height: height,
        modal: true,
        resizable: false,
        autoResize: true,
        stack: false,
        overlay: {
            opacity: 0.5,
            background: "black"
        },
        beforeClose: function(event, ui) {$('#site').remove();$('body').css('overflow','scroll')}
    }).width(width - horizontalPadding).height(height - verticalPadding);
    
    
    
}